//
// Created by 文道江 on 15/11/23.
// Copyright (c) 2015 文道江. All rights reserved.
//

#import "WebViewController.h"
#import "YCXMenu.h"
#import "UIWebView+AFNetworking.h"

@interface WebViewController(){
    NSMutableArray *_menuItems;

    BOOL _showScan;
    BOOL _showShare;
    BOOL _showCopy;
    BOOL _showReload;
    BOOL _showBrowser;

    NSString *_shareTitle;
    NSString *_shareText;
    NSString *_shareUrl;
    NSString *_shareImage;
}

@end

@implementation WebViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    NSDictionary *attributes = @{NSForegroundColorAttributeName : [UIColor whiteColor], NSFontAttributeName : [UIFont systemFontOfSize:16]};
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];

    self.title = @"...";

    [self setUserAgent];

    _webView = [[WVJB_WEBVIEW_TYPE alloc] initWithFrame:self.view.frame];
    _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth;

    _bridge = [HybridBridge bridgeForWebView:_webView webViewDelegate:self controller:self handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"... %@", data);
    }];

    //menu
    [_bridge.javascriptBridge registerHandler:@"changeWebMenu" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"changeWebMenu %@", data);
        if (data){
            _showScan = [data[@"scan"] boolValue];
            _showCopy = [data[@"copy"] boolValue];
            _showReload = [data[@"reload"] boolValue];
            _showShare = [data[@"share"] boolValue];
            _showBrowser = [data[@"browser"] boolValue];
        }
    }];

    [_bridge.javascriptBridge registerHandler:@"setWebShareInfo" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"changeWebMenu %@", data);
        if (data){
            _shareTitle = data[@"title"];
            _shareUrl = data[@"url"];
            _shareText = data[@"text"];
            _shareImage = data[@"image"];

            if (!_shareTitle || [_shareTitle isEqualToString:@""]){
                _shareTitle = _webView.title;
            }

            if (!_shareUrl || [_shareUrl isEqualToString:@""]){
                _shareUrl = _webView.URL.absoluteString;
            }

            if (!_shareText || [_shareText isEqualToString:@""]){
                //_shareText = [_webView stringByEvaluatingJavaScriptFromString:@"(function(){var d = document.head.querySelector(\"meta[name=description]\");return d?d.getAttribute(\"content\"):\"\";})();"];
                //_shareText = _webView.description;
                [_webView evaluateJavaScript:@"(function(){var d = document.head.querySelector(\"meta[name=description]\");return d?d.getAttribute(\"content\"):\"\";})();"
                           completionHandler:^(id result, NSError *error) {
                               _shareText = [result stringValue];
                }];
            }
        }
    }];

    [self.view addSubview:_webView];

    if (_openUrl != nil) {
        [self loadUrl:_openUrl];
    }else{
        [self loadUrl:@"about:blank"];
    }

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage iconWithInfo:TBCityIconInfoMake(@"\U0000e60f", 24, [UIColor whiteColor])] style:UIBarButtonItemStylePlain target:self action:@selector(back:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage iconWithInfo:TBCityIconInfoMake(@"\U0000e61f", 24, [UIColor blackColor])] style:UIBarButtonItemStylePlain target:self action:@selector(menus:)];
}

- (void)viewWillAppear:(BOOL)animated {
    if (self.navigationController){
        self.navigationBarHidden = self.navigationController.navigationBarHidden;
        self.navigationController.navigationBarHidden = NO;
        self.automaticallyAdjustsScrollViewInsets = YES;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    if (self.navigationController){
        self.navigationController.navigationBarHidden = self.navigationBarHidden;
        self.automaticallyAdjustsScrollViewInsets = !self.navigationBarHidden;
    }
}

- (void)loadUrl:(NSString *)url {
    NSLog(@"_openUrl %@", _openUrl);
    [self loadURL:[NSURL URLWithString:url]];
}

- (void)loadURL:(NSURL *)url {
    [self loadRequest:[NSURLRequest requestWithURL:url]];
}

- (void)loadRequest:(NSURLRequest *)request {
    if (_webView){
        [_webView loadRequest:request];
    }
}

- (void)openWindowWithURL:(NSString *)url {
    WebViewController *webViewController = [self mutableCopy];
    webViewController.openUrl = url;
    if (self.navigationController) {
        [self.navigationController pushViewController:webViewController animated:YES];
    } else {
        [self presentViewController:webViewController animated:YES completion:^{

        }];
    }
}

- (NSString*) setUserAgent{
    UIDevice *device = [UIDevice currentDevice];
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];

    NSString *userAgent = [NSString stringWithFormat:@"Mozilla/5.0 (%@; CPU %@ %@ like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/%@ MSNative %@ WebBorwser", device.name, device.systemName,device.systemVersion, device.systemVersion, infoDictionary[@"CFBundleShortVersionString"]];
    [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": userAgent}];
    return userAgent;
}

- (void)back:(id)sender {
    if (_webView.canGoBack){
        [_webView goBack];
    }else{
        if (self.navigationController){
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }
}

- (void)menus:(id)sender{

    AppTheme *appTheme = [HybridBridge defaultHybridBridge].theme;
    UIColor *bgColor = appTheme == nil ? [UIColor colorWithRed: 1.0f green:0.4 blue:0.0 alpha: 1] : appTheme.primaryColor;
    UIColor *color = appTheme == nil ? [UIColor whiteColor] : appTheme.color;

    [YCXMenu setTintColor:bgColor];

    [YCXMenu setHasShadow:YES];

    if (_menuItems == nil){
        if (_showShare && NSClassFromString(@"HybridSocialAction")) {
            [self addMenuItem:@"分享" Image:[UIImage iconWithInfo:TBCityIconInfoMake(@"\U0000e629", 24, color)] Tag:1001 Color:color];
        }
        if (_showScan && NSClassFromString(@"HybridQRCodeAction")) {
            [self addMenuItem:@"扫一扫" Image:[UIImage iconWithInfo:TBCityIconInfoMake(@"\U0000e60e", 24, color)] Tag:1002 Color:color];
        }

        [self addMenuItem:@"重新载入" Image:[UIImage iconWithInfo:TBCityIconInfoMake(@"\U0000e61e", 24, color)] Tag:1005 Color:color];

        if (_showCopy)[self addMenuItem:@"复制链接" Image:[UIImage iconWithInfo:TBCityIconInfoMake(@"\U0000e636", 24, color)] Tag:1003 Color:color];

        if (_showBrowser)[self addMenuItem:@"在浏览器打开" Image:[UIImage iconWithInfo:TBCityIconInfoMake(@"\U0000e627", 24, color)] Tag:1004 Color:color];
    }

    if ([YCXMenu isShow]){
        [YCXMenu dismissMenu];
    } else {
        [YCXMenu showMenuInView:self.view fromRect:CGRectMake(self.view.frame.size.width - 50, self.navigationController.navigationBar.frame.size.height + 20, 50, 0) menuItems:_menuItems selected:^(NSInteger index, YCXMenuItem *item) {
            [YCXMenu dismissMenu];
            if (item.tag == 1001){
                [_bridge executeAction:@"Social/showShareActionSheet" Params:@{
                        @"title": _shareTitle,
                        @"text": _shareText,
                        @"url": _shareUrl,
                        @"image": _shareImage
                } Handler:^(id responseData) {
                    if(responseData != nil && [responseData[@"status"] boolValue]){
                        [_bridge executeAction:@"CoreUI/showToast" Params:@{@"message" : @"分享成功!"} Handler:nil];
                    }
                }];
            }else if (item.tag == 1002){
                [_bridge executeAction:@"QRCode/Scan" Params:@{
                        @"title": @"扫一扫打开网站"
                } Handler:^(id responseData) {
                    NSLog(@"%@", responseData);
                    if(responseData != nil && [responseData[@"status"] boolValue] && responseData[@"data"] != nil){
                        NSString *url = responseData[@"data"];
                        [self loadUrl:url];
                    }
                }];
            }else if (item.tag == 1003){
                [UIPasteboard generalPasteboard].string = _webView.URL.absoluteString;
                [_bridge executeAction:@"CoreUI/showToast" Params:@{@"message" : @"链接已复制到剪贴板"} Handler:nil];
            }else if(item.tag == 1004){
                [[UIApplication sharedApplication] openURL:_webView.URL];
            }else if(item.tag == 1005){
                [_webView reload];
            }
        }];
    }
}

- (void)addMenuItem:(NSString *)title Image:(UIImage *)image Tag:(NSInteger)tag Color:(UIColor *)color {

    if (_menuItems == nil)_menuItems = [NSMutableArray arrayWithCapacity:2];
    YCXMenuItem *menuItem = [YCXMenuItem menuItem:title
                                            image:image
                                              tag:tag
                                         userInfo:@{@"title": title}];
    if (color){
        menuItem.foreColor = color;
    }
    menuItem.alignment = NSTextAlignmentLeft;
    [_menuItems addObject: menuItem];
}

#pragma mark webview delegate

- (void)webViewDidStartLoad:(UIWebView *)webView {
    //self.title = @"...";
}

/*- (void)webViewDidFinishLoad:(UIWebView *)webView {

    NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    if (title && title.length > 0){
        self.title = title;
    }else{
        self.title = @"浏览网页";
    }

    [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.deviceWidth=%f;window.deviceHeight=%f;window.nativeReady=true;", webView.frame.size.width, webView.frame.size.height]];
}*/

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    NSString *title = webView.title;
    if (title && title.length > 0){
        self.title = title;
    }else{
        self.title = @"浏览网页";
    }

    [webView evaluateJavaScript:[NSString stringWithFormat:@"window.deviceWidth=%f;window.deviceHeight=%f;window.nativeReady=true;", webView.frame.size.width, webView.frame.size.height] completionHandler:nil];
}

@end